package com.ifacebox.vcam4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author znn
 */
public class VCamTakeService {
    private static final Log log = LogFactory.getLog(VCamRendererService.class);
    private static final int CONNECT_TIMEOUT = 1000 * 15;
    private static final int WRITE_TIMEOUT = 1000 * 15;
    private static final int READ_TIMEOUT = 1000 * 15;
    public static final String VCAM_TAKE_IP = "127.0.0.1";
    public static final int VCAM_TAKE_PORT = 9526;
    public static final String VCAM_TAKE_URL = "http://%s:%s/ifacebox/GetOneFrameCameraVideo";
    private final OkHttpClient httpClient;

    public VCamTakeService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
    }

    public VCamTake take(String terminalIp) {
        String url = String.format(VCAM_TAKE_URL
                , terminalIp == null || terminalIp.isEmpty() ? VCAM_TAKE_IP : terminalIp
                , VCAM_TAKE_PORT);
        if (log.isInfoEnabled()) {
            log.info(String.format("请求拍照服务器：【%s】", url));
        }
        try (Response response = this.httpClient.newCall(new Request.Builder().url(url).build()).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return JSON.parseObject(response.body().string(), VCamTake.class);
            } else {
                throw new IOException(String.format("%d:%s", response.code(), response.message()));
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(String.format("请求拍照服务器地址异常：【%s】", e.getMessage()));
            }
            return null;
        }
    }
}
